import Vue from 'vue'
import VueRouter from 'vue-router'
import Reg from '@/views/Reg/Reg.vue'
import Login from '@/views/Login/Login.vue'
import Main from '@/views/Main/Main.vue'
import store from '@/store'
import home from '@/views/Menus/Home/Home.vue'
import UserInfo from '@/views/Menus/User/UserInfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
import UserPwd from '@/views/Menus/User/UserPwd.vue'
import ArtCate from '@/views/Menus/Article/ArtCate.vue'
import ArtList from '@/views/Menus/Article/ArtList.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/Reg',
    component: Reg
  },
  {
    path: '/Login',
    component: Login
  }, {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: home
      },
      {
        path: 'user-info',
        component: UserInfo
      },
      {
        path: 'user-avatar',
        component: UserAvatar
      },
      {
        path: 'user-pwd',
        component: UserPwd
      },
      {
        path: 'art-cate',
        component: ArtCate
      },
      {
        path: 'art-list',
        component: ArtList
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 注册全局前置守卫
// 传入一个回调函数
// 回调函数有3个参数
// 参数1 to  到哪里去
// 参数2 from  从哪里来
// 参数3 next 是否放行
router.beforeEach((to, from, next) => {
// 需求:如果没有token 不允许进入除了登录注册以外的所有页面
// 1, 没有token
// 2. 进入的页面不是登录 与 注册
  if (!store.state.user.token && to.path !== '/login' && to.path !== '/reg') {
    Vue.prototype.$message.error('请登录')
    return next('/login')
  }
  next()
}
)

export default router
